
package com.example.filtransfer.client;

import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

import com.example.filetransfer.publicsource.Log;

public class DirectoryWatcher extends Thread {
    private static final String TAG = "DirectoryWatcher";
    private String mPath = null;
    private FileVersionUtil mFileVersionUtil = null;

    public DirectoryWatcher(String path) {
        mPath = path;
        mFileVersionUtil = new FileVersionUtil();
    }

    public void run() {
        try {
            WatchService watchService = FileSystems.getDefault().newWatchService();
            Path path = Paths.get(mPath);
            path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
                    StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
            while (true) {
                WatchKey key = watchService.take();
                // Dir changed,write with new version.
                key.pollEvents();
                String version = mFileVersionUtil.writeVerion(null);
                Log.d(TAG, "file changed update version:" + version);
                key.reset();
            }
        } catch (Exception e) {
        }
    }

    public static void main(String[] args) {
        new DirectoryWatcher("E:\\music").start();
    }
}
